package com.example.administrator.xtu_community.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;


import androidx.appcompat.app.AppCompatActivity;

import com.example.administrator.xtu_community.MainActivity;
import com.example.administrator.xtu_community.R;
import com.example.administrator.xtu_community.bean.Note;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.textfield.TextInputLayout;

import org.litepal.crud.DataSupport;

import java.io.IOException;
import java.time.LocalTime;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String[] DUMMY_CREDENTIALS = new String[]{
            "foo@example.com:hello", "bar@example.com:world"
    };
    private static final String TAG = "LoginActivity";

    // Keep track of the login task to ensure we can cancel it if requested.
    private UserLoginTask mAuthTask = null;

    private AutoCompleteTextView mUserNameView;
    private TextInputLayout input_user_name, input_password;
    private EditText mPasswordView;
    private View mProgressView;
    private Button login_button;
    private int count = 0;
    boolean isHide = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // changeView()方法中包含加载布局
        // 根据现在的时间刷新界面UI
        changeView();
        initView();
        testNet();
    }

    public void testNet(){
        String url = "https://www.baidu.com";
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .get()//默认就是GET请求，可以不写
                .build();
        Call call = okHttpClient.newCall(request);

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Response response = call.execute();
                    Log.d(TAG, "run: " + response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    @SuppressLint("ClickableViewAccessibility")
    public void initView() {
        // 加载条
        mProgressView = findViewById(R.id.progress_login);
        // AutoCompleteTextView(有自动提示功能)
        mUserNameView = findViewById(R.id.tv_user_name);
        //
        mPasswordView = findViewById(R.id.tv_password);

        mPasswordView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // getCompoundDrawables获得一个数组，数组0,1,2,3,对应着左，上，右，下 这4个位置的图片，如果没有就为null
                Drawable drawable = mPasswordView.getCompoundDrawables()[2];
                Drawable drawableOpen = getResources().getDrawable(R.drawable.show_eyes2);
                drawableOpen.setBounds(drawable.getBounds());
                Drawable drawableClose = getResources().getDrawable(R.drawable.close_eyes2);
                drawableClose.setBounds(drawable.getBounds());
                if(drawable == null){
                    return false;
                }
                //如果不是按下事件，不再处理
                if (event.getAction() != MotionEvent.ACTION_DOWN) {
                    return false;
                }
                if (event.getX() > mPasswordView.getWidth() - mPasswordView.getPaddingRight()
                        - drawable.getIntrinsicWidth()){
                    Log.e(TAG, "onTouch: " + isHide );
                    //具体操作
                    if(isHide){
                        isHide = false;
                        mPasswordView.setCompoundDrawables(null, null, drawableOpen, null);
                        // 密码由不可见转为可见
                        mPasswordView.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                        // 将光标设置在最后的字符处，防止光标前后弹跳
                        mPasswordView.setSelection(mPasswordView.getText().length());
                    }
                    else{
                        isHide = true;
                        mPasswordView.setCompoundDrawables(null, null, drawableClose, null);
                        // 密码由可见转为不可见
                        mPasswordView.setTransformationMethod(PasswordTransformationMethod.getInstance());
                        // 将光标设置在最后的字符处，防止光标前后弹跳
                        mPasswordView.setSelection(mPasswordView.getText().length());
                    }
                }
                return false;
            }

        });
        // 账号（mUserNameView的容器）
        input_user_name = findViewById(R.id.input_user_name);
        input_user_name.setHintTextAppearance(R.style.EditScreenTextInputLayoutStyle);
        // 密码（mPasswordView的容器）
        input_password = findViewById(R.id.input_password);
        input_password.setHintTextAppearance(R.style.EditScreenTextInputLayoutStyle);


        // 当用户在该文本框按下Enter时触发
        mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == R.id.btn_login || id == EditorInfo.IME_NULL) {
                    // 尝试登录
                    attemptLogin();
                    // true表留保存软键盘
                    return true;
                }
                // false表示隐藏软键盘
                return false;
            }
        });

        login_button = findViewById(R.id.btn_login);
        // login_button.setTextColor(getResources().getColor(R.color.colorPrimary));
        login_button.setOnClickListener(this);
        Button forgot_password = findViewById(R.id.btn_forgot_password);
        forgot_password.setTextColor(getResources().getColor(R.color.colorPrimary));
        forgot_password.setOnClickListener(this);
        Button register = findViewById(R.id.btn_forgot_register);
        register.setTextColor(getResources().getColor(R.color.colorPrimary));
        register.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login:
                attemptLogin();
                Log.e(TAG, "onClick: " + "点击了登录按钮");
                break;

            case R.id.btn_forgot_password:
                Log.e(TAG, "onClick: " + "点击了忘记按钮");
                Snackbar.make(v, getString(R.string.snackbar_forgot_password), Snackbar.LENGTH_LONG)
                        .setAction("^_^", null).show();
                break;

            case R.id.btn_forgot_register:
                Snackbar.make(v, getString(R.string.snackbar_register), Snackbar.LENGTH_LONG)
                        .setAction("^_^", null).show();
                break;
            default:
                break;
        }
    }


    /**
     * Attempts to sign in or register the account specified by the login form. If there are form errors
     * (invalid email, missing fields, etc.), the errors are presented and no actual login attempt is made.
     */
    private void attemptLogin() {
        if (mAuthTask != null) {
            return;
        }

        // Reset errors.
        input_user_name.setError(null);
        input_password.setError(null);

        // 获得已输入的账号密码
        String userName = mUserNameView.getText().toString();
        String password = mPasswordView.getText().toString();

        boolean cancel = false;
        View focusView = null;

        if (TextUtils.isEmpty(userName)) {
            // 报错账号为空
            input_user_name.setError(getString(R.string.error_no_name));
            focusView = mUserNameView;
            cancel = true;
        } else if (!isPhoneValid(userName) && !isEmailValid(userName)) {
            // 账号不符合格式
            input_user_name.setError(getString(R.string.error_invalid_name));
            focusView = mUserNameView;
            cancel = true;
        } else if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
            // 密码不符合格式
            input_password.setError(getString(R.string.error_invalid_password));
            focusView = mPasswordView;
            cancel = true;
        } else if ((isPhoneValid(userName) || isEmailValid(userName)) && TextUtils.isEmpty(password)) {
            // 密码为空
            input_password.setError(getString(R.string.error_no_password));
            focusView = mPasswordView;
            cancel = true;
        }

        if (cancel) {
            // 出现错误的账号或者密码的View获得焦点
            focusView.requestFocus();
        } else {
            hideInput(login_button);
            // 登录成功，显示Processbar
            mPasswordView.setVisibility(View.VISIBLE);
            mAuthTask = new UserLoginTask(userName, password);
            mAuthTask.execute((Void) null);
        }
    }

    // 账号：电话号码大于等于7且小于等于12
    private boolean isPhoneValid(String userName) {
        return userName.length() >= 7 && userName.length() <= 12;
    }

    // 账号：是否包含"@"

    private boolean isEmailValid(String userName) {
        return userName.contains("@");
    }

    private boolean isPasswordValid(String password) {
        return password.length() >= 4 && password.length() <= 20;
    }

    // 隐藏软键盘

    public void hideInput(View view) {
        InputMethodManager inputMethodManager = (InputMethodManager) this.getSystemService(INPUT_METHOD_SERVICE);
        if (inputMethodManager != null) {
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }




    /**
     * 第一个泛型参数为void表示执行AsyncTask时不要将参数传给后台，第二个参数可表示进度显示单位，第三个参数反馈执行结果
     */
    private class UserLoginTask extends AsyncTask<Void, Void, Boolean> {

        private final String mPhone;
        private final String mPassword;

        UserLoginTask(String userName, String password) {
            mPhone = userName;
            mPassword = password;
        }


        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mProgressView.setVisibility(View.VISIBLE);
        }

        // 方法中的所有代码都会在子线程中运行，我们应该在这里去处理所有的耗时任务。
        // 任务一旦完成就可以通过return语句来将任务的执行结果进行返回
        @Override
        protected Boolean doInBackground(Void... params) {
            // TODO: attempt authentication against a network service.

            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                return false;
            }

            // 用来比对账号密码是否匹配，现在没有数据不会进入内部if语句，相当于直接返回true
            for (String credential : DUMMY_CREDENTIALS) {
                String[] pieces = credential.split(":");
                Log.e(TAG, "doInBackground: " + mPhone);
                Log.e(TAG, "doInBackground: " + pieces[0]);
                if (pieces[0].equals(mPhone)) {
                    // Account exists, return true if the password matches.
                    return pieces[1].equals(mPassword);
                }
            }

            // TODO: register the new account here.
            return true;
        }

        // 当后台任务执行完毕并通过return语句进行返回时，这个方法就很快会被调用。返回的数据会作为参数传递到此方法中，可以利用返回的数据来进行一些UI操作
        @Override
        protected void onPostExecute(final Boolean success) {
            mAuthTask = null;
            mProgressView.setVisibility(View.GONE);

            if (success) {
//                进入主页
//                finish();
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(intent);
            } else {
                input_password.setError(getString(R.string.error_incorrect_password));
                mPasswordView.requestFocus();
            }
        }

        @Override
        protected void onCancelled() {
            mAuthTask = null;
            mProgressView.setVisibility(View.GONE);
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    private void changeView() {
        ImageView imageView;
        TextView textView;


        setContentView(R.layout.activity_login1);
        // 背景图片
        imageView = findViewById(R.id.imageView);
        textView = findViewById(R.id.textView);


        // 根据当前的时间切换背景图片
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            LocalTime nowTime = LocalTime.now();
            Log.e(TAG, "changeView: " + nowTime.toString());
            String[] s = nowTime.toString().split(":");
            if (s[0].compareTo("18") > 0 && s[0].compareTo("4") <= 0) {
                imageView.setImageResource(R.drawable.good_night_img);
                textView.setText("Night");
            }
            else{
                imageView.setImageResource(R.drawable.good_morning_img);
                textView.setText("Morning");
            }
        }

    }



}


